<?php
if(!defined('IN_BSTO')){ die('[ERROR] You cannot load this page directly !!!'); }

define ("MAX_SIZE","500");
Class BookController Extends BaseController {
	private $numOfRow = 5;

	function __construct($registry)
	{
		$this->registry = $registry;
		$this->numOfRow = $this->registry->db->get('configManager')->getByKey('BookTableSize')->get('value');
	}

	public function getExtension($str) {
		$i = strrpos($str,".");
		if (!$i) { return ""; }
		$l = strlen($str) - $i;
		$ext = substr($str,$i+1,$l);
		return $ext;
	}

	public function check_input($data)
	{
		$data = trim($data);
		$data = stripslashes($data);
		$data = htmlspecialchars($data);
		return $data;
	}


	public function index($user, $id = 1)
	{		
		//echo 'okie';
		setcookie('filter2', 0 , time() + 3600*24);
		$this->view($user, $id);
	}

	public function view($user, $page = 1)
	{
		$db = $this->registry->db;

		if(isset($_GET['numRows'])){
			$this->numOfRow = $_GET['numRows'];
		}else if(isset($_GET['curRow'])){
			$this->numOfRow = $_GET['curRow'];
		}

		//for filter
		$tmp = $db->get('bookManager')->getAllBookNames($user);
		$bookName = $this->getNameString($tmp);

		$tmp = $db->get('catManager')->getAllCatNames();
		$catName = $this->getNameString($tmp);

		$tmp = $db->get('userManager')->getAllUserNames();
		$userName = $this->getNameString($tmp);

		$tags = array('bstoContentTitle' => "List of All Books",
					  'bookNameData' => $bookName,
					  'categoryData' => $catName,
					  'userData' => $userName				  	  				 
		);
		if ($user->get('type') == "Normal") {
			$tags['userInputTag'] = '<b>' . $user->get('username') . '</b>';
		}
		else {
			$tags['userInputTag'] = '<input id="filter_user" name="username" class="inp-form" value="{usernameInput}"/>';
		}

		$method = $_SERVER['REQUEST_METHOD'];
		if ( ($method == 'POST') || isset($_GET['filter']) ) {
			if ( ($method == 'POST') ) {
				//for num of row feature
				setcookie('filter2', 1, time() + 3600*24);
				
				if (isset($_POST['bname'])) {
					$bname = $_POST['bname'];
					$_SESSION['bname'] = $bname;
					//echo var_export(addslashes($bname), true);
				}
				else {
					$bname = null;
					unset($_SESSION['bname']);
				}
				if (isset($_POST['category'])) {
					$cat = $_POST['category'];
					$_SESSION['category'] = $cat;
				}
				else {
					$cat = null;
					unset($_SESSION['category']);
				}
				if ($user->get('type') == 'Normal') {
					$username = $user->get("username");
					$_SESSION['username'] = $username;
				}
				else {
					if (isset($_POST['username'])) {
						$username = $_POST['username'];
						$_SESSION['username'] = $username;
					}
					else {
						$username = null;
						unset($_SESSION['username']);
					}
				}

				$res = $this->filter($user, $page, $bname, $cat, $username);
				echo json_encode($res);
			}
			else if (isset($_GET['filter'])) {
				//echo $page;
				$bname = isset($_SESSION['bname']) ? $_SESSION['bname'] : null;
				$cat= isset($_SESSION['category']) ? $_SESSION['category'] : null;
				$username = isset($_SESSION['username']) ? $_SESSION['username'] : null;

				//echo "bname = " . $bname . "cat = " . $cat . " user = " . $username;
				$tags['bnameInput'] = $bname;
				$tags['catInput'] = $cat;
				$tags['usernameInput'] = $username;
				$res = $this->filter($user, $page, $bname, $cat, $username);

				$vbookMod = $this->registry->template->getModule('vbook', $tags);	
						
				$content = str_replace('{bstoTableHeader}', $res['bstoTableHeader'], $vbookMod);
				$content = str_replace('{bstoContent}', $res['bstoContent'], $content);
				$content = str_replace('{bstoPaging}', $res['bstoPaging'], $content);

				$this->registry->template->setMenuKey('book');

				$output = $this->registry->template->getPageContent('index', 'BSTO ACP - Book Management', $content, $tags);

				echo $output;
			}
		}
		else {
				
			$content = "Welcome to Book Control Panel!";

			$tags['bnameInput'] = '';
			$tags['catInput'] = '';
			$tags['usernameInput'] = '';

			$totalBook = $db->get('bookManager')->countBookById($user->get('uid'), $user->get('type'));
			if ($totalBook == 0) {
				$page = 1;
			}
			$numPage = ceil($totalBook/$this->numOfRow);
			if ($numPage == 0){
				$numPage = 1;
			}
			$page = ($page < $numPage) ? $page : $numPage;

			$fst = $this->numOfRow * ($page - 1);

			$arrResult = $db->get('bookManager')->getBookByUserLimit($user->get('uid'), $user->get('type'), $fst, $this->numOfRow);

			$res = $this->getBookTable($user, $arrResult, $numPage, $page, "", "in normal view");
           
            if ($res['bstoContent'] == ""){
                $content = "There is no book!";
            } else {
                $vbookMod = $this->registry->template->getModule('vbook', $tags);
                $content = str_replace('{bstoTableHeader}', $res['bstoTableHeader'], $vbookMod);
			    $content = str_replace('{bstoContent}', $res['bstoContent'], $content);
                $content = str_replace('{bstoPaging}', $res['bstoPaging'], $content);
            }			

			$this->registry->template->setMenuKey('book');

			$output = $this->registry->template->getPageContent('index', 'BSTO ACP - Book Management', $content, $tags);

			echo $output;
		}
	}

	public function delete($user, $page, $id)
	{
		$this->registry->db->get('bookManager')->setDelBookById($id);
			
		$this->linkToPreviousPage($user, $page);
	}

	public function special($user, $page, $id)
	{
		$this->registry->db->get('bookManager')->setSpecialById($id);

		$this->linkToPreviousPage($user, $page);
	}

	public function feature($user, $page, $id)
	{
		$this->registry->db->get('bookManager')->setFeatureById($id);

		$this->linkToPreviousPage($user, $page);
	}

	public function setNumRow($num)
	{
		$this->numOfRow = $num;
	}

	public function add($user, $str = '')
	{
		$tags = array('bstoContentTitle' => "Add Book");

		if($str == 'img'){
			$tags = array('bstoContentTitle' => 'Add Book - <span style = "color : red;">Error: Please choose right format for the picture(jpg, jpeg, png)!</span>');
			$content = $this->printError();
		}else if($str == 'size'){
			$tags = array('bstoContentTitle' => 'Add Book - <span style = "color : red;">Error: Picture exceeds 5MB!"</span>');
			$content = $this->printError();
		} else if ($str == 'title'){
			$tags = array('bstoContentTitle' => 'Add Book - <span style = "color : red;">Error: Please enter the title!"</span>');
			$content = $this->printError();
		} else if ($str == 'weight'){
			$tags = array('bstoContentTitle' => 'Add Book - <span style = "color : red;">Error: Please enter the weight!"</span>');
			$content = $this->printError();
		} else if ($str == 'summary'){
			$tags = array('bstoContentTitle' => 'Add Book - <span style = "color : red;">Error: Please enter the summary!"</span>');
			$content = $this->printError();
		} else if ($str == 'detail'){
			$tags = array('bstoContentTitle' => 'Add Book - <span style = "color : red;">Error: Please enter the detail!"</span>');
			$content = $this->printError();
		} else if ($str == 'category'){
			$tags = array('bstoContentTitle' => 'Add Book - <span style = "color : red;">Error: Please enter the category!"</span>');
			$content = $this->printError();
		}
		if(isset($_GET['numRows'])){
			$this->numOfRow = $_GET['numRows'];
		}
		else if(isset($_GET['curRow'])){
			$this->numOfRow = $_GET['curRow'];
		}
		$method = $_SERVER['REQUEST_METHOD'];
			
		//$user = $this->registry->db->get('userManager')->getCurrentUser();
		if ($method=='POST'){
			$type = "book";

			$uid = $user->get('uid');
			$created = $this->registry->db->get('bookManager')->getNow();

			if(isset($_POST["title"])) {
				$title = strip_tags($_POST["title"]);
				if ($title == "") {
					header("Location: ../add/title");
					exit();
				}
			}
			if (isset($_POST["weight"])){
				$weight = $_POST["weight"];
				if ($weight == ""){
					$weight = $this->registry->db->get('bookManager')->getMaxWeight($uid) + 1;
				}
			}

			if (isset($_POST["summary"])){
				$summary = strip_tags($_POST["summary"]);
				if ($summary == ""){
					header("Location: ../add/summary");
					exit();
				}
			}
			if (isset($_POST["detail"])){
				$detail = strip_tags($_POST["detail"]);
				if ($detail == ""){
					header("Location: ../add/detail");
					exit();
				}
			}
			if (isset($_POST["category"])){
				$category = $_POST["category"];
				if ($category == ""){
					header("Location: ../add/category");
					exit();
				}
			}
			$thumbnail = $_FILES["thumbnail"]["name"];

			$cid = $this->registry->db->get('bookManager')->getIdCategoryByName($category);
			$status = 1;
			$uploadedfile = $_FILES['thumbnail']['tmp_name'];
			$src = '';
			if ($thumbnail)
			{
				$filename = stripslashes($_FILES['thumbnail']['name']);
				$extension = $this->getExtension($filename);
				$extension = strtolower($extension);
				if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") ) {
					header("Location: ../add/img");
					exit();
				}
				else
				{
					$size=filesize($_FILES['thumbnail']['tmp_name']);
					if ($size > MAX_SIZE*1024 * 1024){
						header("Location: ../add/size");
						exit();
					}
					if($extension=="jpg" || $extension=="jpeg" ){
						$uploadedfile = $_FILES['thumbnail']['tmp_name'];
						$src = imagecreatefromjpeg($uploadedfile);

					}else if($extension=="png"){
						$uploadedfile = $_FILES['thumbnail']['tmp_name'];
						$src = imagecreatefrompng($uploadedfile);

					}else {
						$src = imagecreatefromgif($uploadedfile);
					}
					list($width,$height)=getimagesize($uploadedfile);

					$newWidth1 = 333;
					$newHeight1 = 500;
					$newWidth2 = 100;
					$newHeight2 = 150;
					$tmp1=imagecreatetruecolor($newWidth1, $newHeight1);
					$tmp2=imagecreatetruecolor($newWidth2, $newHeight2);
					if($height > $width){
						if( ($height / $width) > (3/2)){

							imagecopyresampled($tmp1,$src,0,0,0,($height * 333 / $width - 500) * $width / 333 / 2, 333, 500, $width, 500 * $width / 333);
							imagecopyresampled($tmp1,$src,0,0,0,($height * 100 / $width - 150) * $width / 100 / 2, 100, 150, $width, 150 * $width / 100);
						}else{

							imagecopyresampled($tmp1,$src,0,0,($width * 500 / $height - 333) * $height / 500 / 2,0, 333, 500, 333/500 * $height , $height);
							imagecopyresampled($tmp2,$src,0,0,($width * 150 / $height - 100) * $height / 150 / 2,0, 100, 150, 100/150 * $height , $height);
						}
					}else{
							
						imagecopyresampled($tmp1,$src,0,0, ($width * $newHeight1 / $height - 333)  * $height / $newHeight1 /2 , 0, 333, 500, 333 * $height / $newHeight1 , $height);
						imagecopyresampled($tmp2,$src,0,0, ($width * $newHeight2 / $height - 100)  * $height / $newHeight2 /2 , 0, 100, 150, 100 * $height / $newHeight2 , $height);
					}
					$destination = dirname(dirname($_SERVER['SCRIPT_FILENAME'])).'/views/images/';
					$filename1 = $destination.  "large/" . $_FILES['thumbnail']['name']  ;
					$filename2 = $destination.  "thumbnail/" .$_FILES['thumbnail']['name'];

					imagejpeg($tmp1,$filename1,100);
					imagejpeg($tmp2,$filename2,100);
					imagedestroy($src);
					imagedestroy($tmp1);
					imagedestroy($tmp2);
				}
			}
			$thumbnailName = $_FILES['thumbnail']['name'];
			$largeName = $_FILES['thumbnail']['name']  ;

			$queryEntity = "INSERT INTO entity(title, type, uid, weight, created, status) VALUES (" . var_export($title, true) . "," .var_export($type, true) . "," .$uid. ",". $weight .", NOW()" .",". $status. ")";

			$this->registry->db->startConnection();

			$this->registry->db->dbQuery($queryEntity);
			$nid = $this->registry->db->get('bookManager')->getMaxId();
			$queryBook = "INSERT INTO book (nid, summary, detail, thumbnail, cid) VALUES ($nid, " .var_export($summary, true). "," . var_export($detail, true) .",". var_export($thumbnailName, true).",". $cid .")";

			$this->registry->db->dbQuery($queryBook);

			$this->registry->db->closeConnection();

			$numBook = $this->registry->db->get('bookManager')->getBookByUser($user->get('uid'), $user->get('type'));

			if (count($numBook) == 1) {
				header("Location: ../view/1");
				exit();
			}
			header("Location: ../add_step_2/new");
			exit();

		} else {

			$tmpContent = $this->registry->template->getModule('abook', $tags);
			$str = '<option value="{value}">{value}</option>';
			$arrResult = $this->registry->db->get('catManager')->getAllName();
			$strContentTotal = '';
			foreach ($arrResult as $ele){
				$strContent = str_replace('{value}', $ele['name'], $str);
				$strContentTotal = $strContentTotal . $strContent;
			}

			$content = str_replace('{bstoCatContent}', $strContentTotal, $tmpContent);
		}

		$this->registry->template->setMenuKey('book');
		$output = $this->registry->template->getPageContent('index', 'BSTO ACP - Add Book', $content, $tags);
		echo $output;
	}

	public function add_step_2($user)
	{
		$method = $_SERVER['REQUEST_METHOD'];
		if ($method == 'POST'){
			//$user = $this->registry->db->get('userManager')->getCurrentUser();
			$nid = $this->registry->db->get('bookManager')->getBookByNewDate($user->get('uid'));
			if (isset($_POST['isRelated'])) {
				$isRelated = $_POST["isRelated"];
			} else {
				$isRelated = array();
			}
			$tags = array('bstoContentTitle' => "Select Related Books Done");
			//echo var_export($isRelated, true);
			if (count($isRelated) != 0){
				foreach ($isRelated as $ele){
					$queryRelated1 = "INSERT INTO related_book VALUE ( $nid ,$ele )";
					$queryRelated2 = "INSERT INTO related_book VALUE ( $ele ,$nid )";
					// $content = $content . $queryRelated1 . $queryRelated2;
					$this->registry->db->dbQuery($queryRelated1);
					$this->registry->db->dbQuery($queryRelated2);

				}
			}
			$this->linkToLastPage($user);
		} else {
			//$user = $this->registry->db->get('userManager')->getCurrentUser();
			$tags = array('bstoContentTitle' => "Select Related Books");
			$content = $this->registry->template->getModule('vRelated', $tags);

			$nid = $this->registry->db->get('bookManager')->getBookByNewDate($user->get('uid'));
			$arrResult = $this->registry->db->get('bookManager')->getBookByUserFilter($user->get('uid'), $user->get('type'));

			$strContent ="";
			$strContentTotal = '';
			$tmpContent = $this->registry->template->getModule('vOneRelated', $tags);

			$id1 = 1;
			foreach ($arrResult as $ele){
				if( $id1%2 == 0 ) {
					$strContent = str_replace('{class}', '', $tmpContent);
				} else {
					$strContent = str_replace('{class}', 'alternate-row', $tmpContent);
				}
				$strContent = str_replace('{BstoId}', $ele['nid'], $strContent);
				$strContent = str_replace('{BstoName}', $ele['title'], $strContent);
				$strContent = str_replace('{BstoCategory}', $ele['name'], $strContent);
				$strContent = str_replace('{BstoUser}', $ele['username'], $strContent);
				$strContent = str_replace('{BstoCreated}', $ele['created'], $strContent);
				$strContent = str_replace('{checked}', '', $strContent);
				$strContentTotal = $strContentTotal . $strContent;
				$id1++;
			}

			$content = str_replace('{BstoContent}', $strContentTotal, $content);


			$this->registry->template->setMenuKey('book');
			$output = $this->registry->template->getPageContent('index', 'BSTO ACP - Add Book : Step 2', $content, $tags);

			echo $output;
		}

	}


	public function edit($user, $page, $id)
	{
		if(isset($_GET['numRows'])){
			$this->numOfRow = $_GET['numRows'];
		}else if(isset($_GET['curRow'])){
			$this->numOfRow = $_GET['curRow'];
		}
		$method = $_SERVER['REQUEST_METHOD'];
		$tags = array('bstoContentTitle' => "Edit Book");
		//$user = $this->registry->db->get('userManager')->getCurrentUser();
		if ($method=='POST'){

			if(isset($_POST["title"])) {
				$title = strip_tags($_POST["title"]);
			}
			if (isset($_POST["weight"])){
				$weight = $_POST["weight"];
			}
			if ($weight == ""){
				$weight = $this->registry->db->get('bookManager')->getMaxWeight($uid) + 1;
			}
			if (isset($_POST["summary"])){
				$summary = strip_tags($_POST["summary"]);
			}
			if (isset($_POST["detail"])){
				$detail = strip_tags($_POST["detail"]);
			}
			if (isset($_POST["category"])){
				$category = $_POST["category"];
			}


			$type = "book";
			$uid = $user->get('uid');
			$change = $this->registry->db->get('bookManager')->getNow();
			$cid = $this->registry->db->get('bookManager')->getIdCategoryByName($category);
			$status = 1;

			$queryEntity = "UPDATE entity
							SET title = " . var_export($title, true). ", weight = $weight, changed = NOW()
							WHERE nid = $id";


			$queryBook = "UPDATE book
					     SET summary = " . var_export($summary, true). ", detail = " . var_export($detail, true) . ", cid = $cid 
					     WHERE nid = $id";

			$this->registry->db->startConnection();
			$this->registry->db->dbQuery($queryEntity);
			$this->registry->db->dbQuery($queryBook);
			$this->registry->db->closeConnection();

			$numBook = $this->registry->db->get('bookManager')->getBookByUser($user->get('uid'), $user->get('type'));

			if (count($numBook) == 1) {
				header("Location: ../../view/1");
				exit();
			}
			header("Location: ../../edit_step_2/$page/$id");

		}else{
			$arr = $this->registry->db->get('bookManager')->getBookById($id);
			if (count($arr) != 0){
				$row = $arr[0];
			} else {
				$row = null;
			}

			$tmpContent = $this->registry->template->getModule('eBook', $tags);
			$str = '<option value="{value}">{value}</option>';
			$strSelected = '<option value="{value}" selected>{value}</option>';
			$arrResult = $this->registry->db->get('catManager')->getAllName();
			$strContentTotal = '';
			foreach ($arrResult as $ele){
				if ($row['name'] == $ele['name']){
					$strContent = str_replace('{value}', $ele['name'], $strSelected);
					$strContentTotal = $strContentTotal . $strContent;
				} else {
					$strContent = str_replace('{value}', $ele['name'], $str);
					$strContentTotal = $strContentTotal . $strContent;
				}
			}

			$arrResult = $this->registry->db->get('bookManager')->getBookByUser($user->get('uid'), $user->get('type'));

			$strContentTotal2 = '';
			$str2 = '<option value="{value}">{value}</option>';

			$content = str_replace('{bstoCatContent}', $strContentTotal, $tmpContent);

			foreach ($arr as $ele){
				$content = str_replace('{title}', $ele['title'], $content);
				$content = str_replace('{weight}', $ele['weight'], $content);
				$content = str_replace('{summary}', $ele['summary'], $content);
				$content = str_replace('{detail}', $ele['detail'], $content);
			}
			$this->registry->template->setMenuKey('book');
			$output = $this->registry->template->getPageContent('index', 'BSTO ACP - Edit Book', $content, $tags);

			echo $output;
		}
	}

	public function edit_step_2($user, $page, $id)
	{
		$tags = array('bstoContentTitle' => "Select Related Books");
		$method = $_SERVER['REQUEST_METHOD'];
		if ($method == 'POST'){
			$this->registry->db->get('bookManager')->delAllRelatedBook($id);
			$uid = $this->registry->db->get('bookManager')->getUserIdByBookId($id);
			//$user = $this->registry->db->get('userManager')->getCurrentUser();
			$nid = $this->registry->db->get('bookManager')->getBookByNewDate2($uid);
			if (isset($_POST['isRelated'])) {
				$isRelated = $_POST["isRelated"];
			} else {
				$isRelated = array();
			}
			$queryDelRelated = "DELETE FROM related_book WHERE nid = $nid OR related = $nid";
			$this->registry->db->dbQuery($queryDelRelated);
			if (count($isRelated) != 0){
				foreach ($isRelated as $ele){

					$queryRelated1 = "INSERT INTO related_book VALUE ( $nid ,$ele )";
					$queryRelated2 = "INSERT INTO related_book VALUE ( $ele ,$nid )";

					$this->registry->db->dbQuery($queryRelated1);
					$this->registry->db->dbQuery($queryRelated2);

				}
			}

			//back to previous page
			//header("Location: ../../view/$page");
			//exit();
			$this->linkToPreviousPage($user, $page);
		} else {
			$uid = $this->registry->db->get('bookManager')->getUserIdByBookId($id);
			//$user = $this->registry->db->get('userManager')->getCurrentUser();
			$tags = array('bstoContentTitle' => "Select Related Books");
			$content = $this->registry->template->getModule('vRelated', $tags);

			$nid = $this->registry->db->get('bookManager')->getBookByNewDate2($uid);
			$arrResult = $this->registry->db->get('bookManager')->getBookByUserFilter2($uid, $user->get('type'));

			$strContent ="";
			$strContentTotal = '';
			$tmpContent = $this->registry->template->getModule('vOneRelated', $tags);

			$id1 = 1;
			foreach ($arrResult as $ele){
				if( $id1%2 == 0 ) {
					$strContent = str_replace('{class}', '', $tmpContent);
				} else {
					$strContent = str_replace('{class}', 'alternate-row', $tmpContent);
				}

				$strContent = str_replace('{BstoId}', $ele['nid'], $strContent);
				$strContent = str_replace('{BstoName}', $ele['title'], $strContent);
				$strContent = str_replace('{BstoCategory}', $ele['name'], $strContent);
				$strContent = str_replace('{BstoUser}', $ele['username'], $strContent);
				$strContent = str_replace('{BstoCreated}', $ele['created'], $strContent);
				if ($this->registry->db->get('bookManager')->checkRelated($ele['nid'], $id) == true){
					$strContent = str_replace('{checked}', 'checked', $strContent);
				} else {
					$strContent = str_replace('{checked}', '', $strContent);
				}
				$strContentTotal = $strContentTotal . $strContent;
				$id1++;
			}

			$content = str_replace('{BstoContent}', $strContentTotal, $content);


			$this->registry->template->setMenuKey('book');
			$output = $this->registry->template->getPageContent('index', 'BSTO ACP - Edit Book : Step 2', $content, $tags);

			echo $output;
		}
	}

	public function printError()
	{
		$tags = array();
		$tmpContent = $this->registry->template->getModule('abook', $tags);
		$str = '<option value="{value}">{value}</option>';
		$arrResult = $this->registry->db->get('catManager')->getAllName();
		$strContentTotal = '';
		foreach ($arrResult as $ele){
			$strContent = str_replace('{value}', $ele['name'], $str);
			$strContentTotal = $strContentTotal . $strContent;
		}
			
		$content = str_replace('{bstoCatContent}', $strContentTotal, $tmpContent);

		return $content;
	}

	public function show($user, $catId, $page)
	{
		$cat = $this->registry->db->get('catManager')->getById($catId)->get('name');
		$_SESSION['category'] = $cat;
		unset($_SESSION['bname']);
		unset($_SESSION['username']);
		header("Location: ../../view/$page?filter=1");
		exit();
	}

	public function getNameString($arr)
	{
		$result = "";
		foreach ($arr as $key => $value) {
			$result .= '"' . trim($value['name']) . '" ,';
		}
		return substr($result, 0, strlen($result) - 1);
	}

	public function filter($user = null, $page = 1, $bname, $cat, $username)
	{
		//$tmp = $user->get('type');

		$db = $this->registry->db;

		$totalBook = $db->get('bookManager')->countFilterBooks($bname, $cat, $username);
		$numPage = ceil($totalBook/$this->numOfRow);
		$numPage = ($numPage > 0) ? $numPage : 1;
		$page = ($page < $numPage) ? $page : $numPage;
		$fst = $this->numOfRow * ($page - 1);

		$bookArray = $db->get('bookManager')->getFilterBooksLimit($bname, $cat, $username, $fst, $this->numOfRow);

		$result = $this->getBookTable($user, $bookArray, $numPage, $page, "&filter=1", 'test');

		return $result;
	}

	public function getBookTable($user, $arr, $numPage, $page = 1, $filter = "" , $test = "")
	{
		//echo $user->get('type');
		//echo $numPage;

		$tags = array();
		$db = $this->registry->db;

//		$user = $db->get('userManager')->getCurrentUser();

		$path = BSTO_ROOT_PATH . "book";

		if ($user->get('type') == 'Normal'){
			$tmpContent = $this->registry->template->getModule('vOnebook', $tags);
		} else {
			$tmpContent = $this->registry->template->getModule('vOnebook2', $tags);
		}

		//$test = 0;

		$strContent ="";
		$strContentTotal = '';
		$id1 = 0;
		if (!empty($filter)) {
			$bstoFilter = '?filter=1';
		} else {
			$bstoFilter = '';
		}
		foreach ($arr as $ele){
			if( $id1%2 == 0 ) {
				$strContent = str_replace('{class}', '', $tmpContent);
			} else {
				$strContent = str_replace('{class}', 'alternate-row', $tmpContent);
			}
			if ( isset($ele['feature']) && ($ele['feature'] == 1) ) {
				$strContent = str_replace('{iconFeat}', 'icon-52', $strContent);
			} else {
				$strContent = str_replace('{iconFeat}', 'icon-5', $strContent);
			}
			if ( isset($ele['special']) && $ele['special'] == 1){
				$strContent = str_replace('{iconSpec}', 'icon-32', $strContent);
			} else {
				$strContent = str_replace('{iconSpec}', 'icon-3', $strContent);
			}

			$strContent = str_replace('{BstoId}', $ele['nid'], $strContent);
			$strContent = str_replace('{BstoName}', $ele['title'], $strContent);
			$strContent = str_replace('{BstoCategory}', $ele['name'], $strContent);
			$strContent = str_replace('{BstoUser}', $ele['username'], $strContent);
			$strContent = str_replace('{BstoCreated}', $ele['created'], $strContent);
			$strContent = str_replace('{BstoPage}', $page, $strContent);
			$strContent = str_replace('{BstoFilter}', $bstoFilter, $strContent);
			$strContentTotal = $strContentTotal . $strContent;
			$id1++;
		}
		
		$strContentTotal = str_replace('{path}', $path, $strContentTotal);
		
		//paging
		$pageLeft = $page - 1;
		if ($pageLeft <= 0){
			$pageLeft = 1;
		}
		$pageLeft = $path. "/view/". $pageLeft . "?curRow=" . $this->numOfRow;
		$pageFarLeft = 1;
		$pageFarLeft = $path. "/view/". $pageFarLeft . "?curRow=" . $this->numOfRow;
		$pageRight = $page + 1;
		if ($pageRight > $numPage){
			$pageRight = $numPage;
		}
		$pageRight = $path. "/view/". $pageRight . "?curRow=" . $this->numOfRow;
		$pageFarRight = $numPage;
		$pageFarRight = $path. "/view/". $pageFarRight . "?curRow=" . $this->numOfRow;

		$tags['page'] = $page;
		$tags['pageLeft'] = ($numPage > 1) ? ('"' . $pageLeft . $filter . '"') : '';
		$tags['pageFarLeft'] = ($numPage > 1) ? ('"' . $pageFarLeft . $filter . '"') : '';
		$tags['pageRight'] = ($numPage > 1) ? ('"' . $pageRight . $filter . '"') : '';
		$tags['pageFarRight'] = ($numPage > 1) ? ('"' . $pageFarRight . $filter . '"') : '';
		$tags['href'] = ($numPage > 1) ? 'href=' : '';
		$tags['numPage'] = $numPage;
		
		$tableHeader = $this->registry->template->getModule('bookTableHeader', array());
		$pagingContent = $this->registry->template->getModule('vpaging', $tags);

		return array('bstoTableHeader' => $tableHeader, 
				     'bstoContent' => $strContentTotal, 
				     'bstoPaging' => $pagingContent, 
				     'test' => $test);
	}

	public function viewStats($user, $id)
	{
		$tags = array('bstoContentTitle' => "Book Statistic");

		if(isset($_POST["from"])) {
			$from = $_POST["from"];
		} else {
			$lastWeek  = mktime(0, 0, 0, date("m")  , date("d")-7, date("Y"));
			$from = date( 'd-M-Y', $lastWeek );
		}
		if(isset($_POST["to"])) {
			$to = $_POST["to"];
		} else {
			$to = date("d-M-Y");
		}

		if (strtotime($from) > strtotime($to)){
			$lastWeek  = mktime(0, 0, 0, date("m")  , date("d")-7, date("Y"));
			$from = date( 'd-M-Y', $lastWeek );
			$to = date("d-M-Y");

		}
			
		$exampleArr = $this->registry->db->get('bookManager')->getLSRByIdLimit($id, $from, $to);
			
		$resultArr = $this->input($exampleArr);

        if (count($resultArr) == 0){            
            $content = $this->registry->template->getModule('nodataStat', $tags);
            $content = str_replace('{defaultFrom}', $from, $content);
    		$content = str_replace('{defaultTo}', $to, $content);
            //$content = 'There is no database at this time!';
        } else {
                //====================================================
    		$titlebook = $this->registry->db->get('bookManager')->getTitleBook($id);
    		$exampleArr['title'] = $titlebook;
    		$bstoPath = realpath(dirname(__FILE__));
    		$serialized = serialize($exampleArr);
    		$fp = fopen($bstoPath.'/objects_cache/test.ser', 'w');
    		fwrite($fp, $serialized);
    		
    		//====================================================
    
    		$tempContent = $this->registry->template->getModule('vBookStats', $tags);
    		$xAsis = '';
    		$like = '';
    		$share = '';
    		$retweet = '';
    		for ($i = 0; $i<count($resultArr); $i++){
    			$xAsis = $xAsis. var_export($resultArr[$i]["date"], true). ", ";
    		}
    		for ($i = 0; $i<count($resultArr); $i++){
    			$like = $like. $resultArr[$i]["like"]. ", ";
    		}
    		for ($i = 0; $i<count($resultArr); $i++){
    			$share = $share. $resultArr[$i]["share"]. ", ";
    		}
    		for ($i = 0; $i<count($resultArr); $i++){
    			$retweet = $retweet. $resultArr[$i]["retweet"] . ", ";
    		}
    		$xAsis = substr($xAsis, 0, -2);
    		$like = substr($like, 0, -2);
    		$share = substr($share, 0, -2);
    		$retweet = substr($retweet, 0, -2);
    		//echo(var_export($xAsis, true));
    		//get information for table (using $exampleArr)
    
    		$id1 = 0;
    		$allDate = '';
    		//echo var_export($exampleArr, true);
    			
    		$numArr = count($exampleArr);
    		foreach($exampleArr as $ele){
    			if ($id1 != ($numArr - 1)){
    				//echo var_export($ele, true);
    				$oneDate = $this->registry->template->getModule('vOneStat', $tags);
    				if( $id1%2 == 0 ) {
    					$oneDate = str_replace('{class}', '', $oneDate);
    				} else {
    					$oneDate = str_replace('{class}', 'alternate-row', $oneDate);
    				}
    				$oneDate = str_replace('{BstoDate}', $ele['date'], $oneDate);
    				$oneDate = str_replace('{BstoLike}', $ele['like'], $oneDate);
    				$oneDate = str_replace('{BstoShare}', $ele['share'], $oneDate);
    				$oneDate = str_replace('{BstoRetweet}', $ele['retweet'], $oneDate);
    				$allDate = $allDate . $oneDate;
    				$id1 ++;
    			}
    		}
    		//echo var_export($exampleArr, true);
    		$table = $this->registry->template->getModule('vMenuStats', $tags);
    		$table = str_replace('{BstoContent}', $allDate, $table);
    
    
    		// end getting information for table
    		$content = str_replace('{defaultFrom}', $from, $tempContent);
    		$content = str_replace('{defaultTo}', $to, $content);
    		$content = str_replace('{MyxAxis}', $xAsis, $content);
    		$content = str_replace('{likeFB}', $like, $content);
    		$content = str_replace('{shareFB}', $share, $content);
    		$content = str_replace('{retweetTT}', $retweet, $content);		
    		$content = str_replace('{tableContent}', $table, $content); 
            $content = str_replace("{bookName}", $exampleArr['title'], $content); 
        }


		$output = $this->registry->template->getPageContent('index', 'Book Statistic', $content, $tags);

		echo $output;
			



	}

	public function input($arr)
	{
		$resultArr = array();
		$count = count($arr);
		$offset = floor($count/7);
		if ($offset == 0){
			$offset = 1;
		}
		if ($count >= 7){
			for ($i = 0; $i< 7; $i++){
				$resultArr[$i] = $arr[$i*$offset];
			}
		} else {
			for ($i = 0; $i< $count; $i++){
				$resultArr[$i] = $arr[$i*$offset];
			}
		}
		// echo (var_export($resultArr, true));
		return $resultArr;
	}

	public function linkToLastPage($user)
	{
		$db = $this->registry->db;
		//$user = $db->get('userManager')->getCurrentUser();
		$total = $db->get('bookManager')->countBookById($user->get('uid'), $user->get('type'));
		$page = ceil($total/$this->numOfRow);
		header("Location: ../view/$page");
		exit();
	}

	public function linkToPreviousPage($user, $page)
	{
		$db = $this->registry->db;
		//$user = $db->get('userManager')->getCurrentUser();
		$total = $db->get('bookManager')->countBookById($user->get('uid'), $user->get('type'));
		$page = ($page <= ceil($total/$this->numOfRow)) ? $page : $total/$this->numOfRow;
		if (isset($_GET['filter'])) {
			$filter = '?filter=1';
		} else {
			$filter = '';
		}
		header("Location: ../../view/$page" . $filter);
		exit();
	}

}
?>
